package br.com.gerenciador_recursos.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import br.com.gerenciador_recursos.ProjectAlreadyExistNameException;
import br.com.gerenciador_recursos.GerencidorRecursosBusinessException;
import br.com.gerenciador_recursos.NoSuchProjectException;
import br.com.gerenciador_recursos.RequiredFieldException;
import br.com.gerenciador_recursos.model.Project;

public class ProjectLocalServiceUtil {

	private static List<Project> projects;
	
	static{
		projects = new ArrayList<Project>(); 
	}
	
	public static Project add(String nome, String descricao, Date inicioPrevisto, Date terminoPrevisto) throws GerencidorRecursosBusinessException{
		
		validate(true, null, nome, descricao, inicioPrevisto, terminoPrevisto);
		
		Project project = new Project(IDGeneratorUtil.increment(), nome, descricao, inicioPrevisto, terminoPrevisto);
		
		projects.add(project);
		
		return project;
	}
	
	public static Project update(int projectId, String nome, String descricao, Date inicioPrevisto, Date terminoPrevisto) throws GerencidorRecursosBusinessException{
		
		Project project = findByPrimaryKey(projectId);
		
		validate(false, project, nome, descricao, inicioPrevisto, terminoPrevisto);
		
		projects.remove(project);
		
		project = new Project(projectId, nome, descricao, inicioPrevisto, terminoPrevisto);
		
		projects.add(project);
		
		return project;
	}
	
	public static void delete(int projectId) throws NoSuchProjectException{
		
		Project project = findByPrimaryKey(projectId);
		
		projects.remove(project);
		
	}
	
	
	public static Project findByPrimaryKey(int projectId) throws NoSuchProjectException{
		
		Project project = fetchByPrimaryKey(projectId);
		
		if(project!=null)
			return project;
		
		throw new NoSuchProjectException();
	}
	
	public static Project fetchByPrimaryKey(long projectId){
		
		for (Project project : projects) {
			if(project.getProjectId() == projectId)
				return project;
		}
		
		return null;
	}

	public static Project findByNome(String name, boolean equal){
		
		for (Project project : projects) {
			if(equal && project.getNome().trim().equals(name.trim()))
				return project;
			else if(project.getNome().indexOf(name.trim()) > -1)
				return project;
		}
		
		return null;
	}
	
	private static void validate(boolean isNew, Project oldProject, String nome, String descricao, Date inicioPrevisto, Date terminoPrevisto) throws GerencidorRecursosBusinessException{
		
		if(nome == null || nome.trim().equals(""))
			throw new RequiredFieldException();
		
		Project project = findByNome(nome, true);
		
		if (project != null && project.equals(oldProject)) {
			throw new ProjectAlreadyExistNameException();
		}
		
		if (isNew) {
			
		} else {

		}
		
	}
	
	public static List<Project> findAll(){
		
		return new ArrayList<Project>(projects);
	}
}
